package com.ucom.deadlock;
import java.io.*;

public class DeadLocker {

	public void createDeadLock(int maxThreads, int maxTimeout) {
		
		System.out.println("Demonstrating deadlocks with " + 2
				+ " threads and max time out = " + maxTimeout * 10);
		String[] deadLockQueries = {
		// SESSION_ID=5, LINE_NO=3
				"update USAGE_HISTORY set SESSION_ID=%d where USER_ID in (select USER_ID from USAGE_HISTORY where LINE_NO=%d)",
				// LINE_NO=3, SESSION_ID=5
				"update USAGE_HISTORY set LINE_NO=%d where USER_ID in (select USER_ID from USAGE_HISTORY where SESSION_ID=%d)" };
		int sessionId = 0, lineNo = 0;

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		try {
			System.out.println("Enter seesion ID:");
			sessionId = Integer.parseInt(br.readLine());
			System.out.println(sessionId + "Enter Line number:");
			lineNo = Integer.parseInt(br.readLine());
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		ThreadGroup deadLockThreads = new ThreadGroup("DeadlockQueries");
		
		for (int i = 1; i <= maxTimeout; i++) {
			Thread t1 = new Thread(deadLockThreads, new Client(String.format(
					deadLockQueries[0], sessionId, lineNo), 10 * i), "t1");
			Thread t2 = new Thread(deadLockThreads, new Client(String.format(
					deadLockQueries[1], lineNo, sessionId), 10 * i), "t2");

			t1.start();
			t2.start();
			

			while (deadLockThreads.activeCount() > 0) {
				try {
					Thread.sleep(1000);

					System.out.println("Monitor Thread:"
							+ System.currentTimeMillis() + " : "
							+ deadLockThreads.activeCount()
							+ " threads are active now");

				} catch (InterruptedException e) {
					System.out.println("Main thread Interrupted");
				}

			}
			System.out
					.println("Main thread Completed Execution for waiting time = "
							+ 10 * i);
		}
	}
}
